package com.corpgovernment.common.utils;

import cn.hutool.http.HttpRequest;
import com.ctrip.corp.obt.generic.utils.StringUtils;
import com.ctrip.framework.apollo.Config;
import com.ctrip.framework.apollo.ConfigService;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;
import java.net.Proxy;

@Slf4j
public class HttpHuToolUtils {

    /**
     * 使用工具类hutool
     * 1.工具自带忽略
     * @param name
     * @param url
     * @param json
     * @return
     */
    public static String httpHuToolPost(String name, String url, String json){
        StringBuilder requestLog = new StringBuilder();
        try {
            Config config = ConfigService.getConfig("corpgovernment.common");
            String serverUrl = config.getProperty("proxyUrl", "");
            String serverPort = config.getProperty("proxyPort", "");
            long startTime = System.currentTimeMillis();
            String result = null;
            if (StringUtils.isNotBlank(serverUrl)){
                Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(serverUrl, Integer.parseInt(serverPort)));
                result = HttpRequest.post(url).setProxy(proxy).body(json).execute().body();
            } else {
                result = HttpRequest.post(url).body(json).execute().body();
            }
            requestLog.append("名称：" + name);
            requestLog.append(System.lineSeparator()).append("耗时：" + (System.currentTimeMillis()-startTime));
            requestLog.append(System.lineSeparator()).append("地址：" + url);
            requestLog.append(System.lineSeparator()).append("请求：" + json);
            requestLog.append(System.lineSeparator()).append("响应：" + result);
            return result;
        }catch (Exception e){
            log.error("远程调用异常：{}", e);
        }finally {
            log.info("{}", requestLog);
        }
        return "";
    }
}
